//
//  STKeyFrameViewController.m
//  KeyframeAndGroupAnimation
//
//  Created by Stan on 2017-02-19.
//  Copyright © 2017 stan. All rights reserved.
//

#import "STKeyFrameViewController.h"

@interface STKeyFrameViewController ()
@property (weak, nonatomic) IBOutlet UIView *yellowView;

@property(strong,nonatomic)UIImageView *planeImageView;


@end

@implementation STKeyFrameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //---------------step3:添加动画到要作用的layer上
    //在橙色的View添加抖动的动画。重要事情说三遍：动画一定要加载layer上！动画一定要加载layer上！动画一定要加载layer上！
    [self.yellowView.layer addAnimation:[self shakeAni] forKey:nil];
    
    
    //将小飞机添加到视图上
    [self.view addSubview:self.planeImageView];
    //设置小飞机的位置
    self.planeImageView.center = self.view.center;
    //        为小飞机同时添加抖动的动画和椭圆路径旋转的动画
    [self.planeImageView.layer addAnimation:[self shakeAni] forKey:nil];
    [self.planeImageView.layer addAnimation:[self ovalAni] forKey:nil];
    
}





#pragma mark - 动画


/**
 抖动的动画
 
 @return 抖动的动画
 */
- (CAKeyframeAnimation *)shakeAni{
    //---------------step1:创建关键帧动画对象
    CAKeyframeAnimation *shakeAni = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
    //---------------step2:设置动画属性
    //让动画先左旋转-M_PI_4 / 5，再右旋转同样的度数，再左旋转。这样就动起来了
    shakeAni.values = @[@(-M_PI_4 / 5),@(M_PI_4 / 5),@(-M_PI_4 / 5)];
    
    shakeAni.duration = 0.25;
    //设置动画重复次数
    shakeAni.repeatCount = CGFLOAT_MAX;
    
    return shakeAni;
}


///走椭圆形状的动画
- (CAKeyframeAnimation *)ovalAni{
    //        创建关键帧动画对象。按照指定的路径进行移动，所以需要设置为position
    CAKeyframeAnimation *ovalAni = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    //        创建一个椭圆的beziperPath
    UIBezierPath *ovalPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(100, 100, 200, 500)];
    //        把路径添加到动画上
    ovalAni.path = ovalPath.CGPath;
    //        动画播放时长
    ovalAni.duration = 4;
    //        动画重复次数
    ovalAni.repeatCount = CGFLOAT_MAX;
    //        动画的计算模式
    ovalAni.calculationMode = kCAAnimationPaced;
    //        动画是否沿着路径旋转
    ovalAni.rotationMode = kCAAnimationRotateAutoReverse;
    
    return ovalAni;
}




#pragma mark - 懒加载
- (UIImageView *)planeImageView{
    if (!_planeImageView) {
        _planeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"hero1"]];
        
        _planeImageView.backgroundColor = [UIColor whiteColor];
    }
    return _planeImageView;
}

@end
